[设计模式]之八:中介者模式


定义

用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。

UML

示例代码

// 比如两个同事分别熟悉CTS和SElinux的问题,现在要找他们协助,就需要找PM协调
// 同事之间不一定都认识,但PM肯定认识。所以PM作为中介者
interface Mediator {
    public void send(String msg, Colleague colleague);
}
// PM认识所有同事,所以会持有同事们的实例,然后管理同事
public class ConcreteMediator implements Mediator {

    private ConcreteColleague1 tom;
    private ConcreteColleague2 jerry;

    public void setTom(ConcreteColleague1 tom) {
        this.tom = tom;
    }

    public void setJerry(ConcreteColleague2 jerry) {
        this.jerry = jerry;
    }

    @Override
    public void send(String msg, Colleague colleague) {
        // TODO Auto-generated method stub
        if (colleague.getClass().equals(tom.getClass())) {
            jerry.notify(msg);
        } else {
            tom.notify(msg);
        }
    }

}
//同事只认识PM  由PM转发消息
abstract class Colleague {
    protected Mediator mediator;

    public Colleague(Mediator mediator) {
        this.mediator = mediator;
    }
}
public class ConcreteColleague1 extends Colleague {

    public ConcreteColleague1(Mediator mediator) {
        super(mediator);
    }

    public void send(String msg) {
        mediator.send(msg, this);
    }

    public void notify(String msg) {
        System.out.println("Hi Tom: " + msg);
    }
}
public class ConcreteColleague2 extends Colleague {

    public ConcreteColleague2(Mediator mediator) {
        super(mediator);
    }

    public void send(String msg) {
        mediator.send(msg, this);
    }

    public void notify(String msg) {
        System.out.println("Hi Jerry: " + msg);
    }

}
//客户代码
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ConcreteMediator mediator = new ConcreteMediator();

        ConcreteColleague1 tom = new ConcreteColleague1(mediator);
        ConcreteColleague2 jerry = new ConcreteColleague2(mediator);

        mediator.setTom(tom);
        mediator.setJerry(jerry);

        tom.send("Could you do the CTS job?");
        jerry.send("Could you do the SElinux job?");
    }
//输出
Hi Jerry: Could you do the CTS job?
Hi Tom: Could you do the SElinux job?

评价

当系统出现多对多交互复杂的对象群时,不要急着使用中介者模式,而要先反思你的系统在设计上是不是合理。

优点:
减少各个Colleague之间的耦合,使得可以独立地改变和复用各个Colleague类和Mediator
缺点:
Mediator实现过于复杂

计算器就是中介者模式的实现,所有按键以及屏幕互相不了解,中介者处理按键结果给屏幕显示

适用于一组对象用定义良好但是复杂的方式进行通信的场合


文章作者: Wossoneri
版权声明: 本博客所有文章除特別声明外,均采用 CC BY-NC 4.0 许可协议。转载请注明来源 Wossoneri !
评论
  目录